import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { addRefundAction } from './index';
import moment from 'moment';
import { Tooltip, Icon, Modal } from 'antd';
import { CommonTable } from 'components';
import styles from './AddRefund.less';
import SearchList from './SearchList/SearchList';
import AddModal from './AddModal/AddModal';
import { orderStatus, axios } from 'utils';

const getParams = () => {
    return {
        payType: {
            value: ''
        },
        payName: {
            value: '1'
        },
        totalMoney: {
            value: 0.01
        },
        payTradeNo: {
            value: ''
        },
        payTime: {
            value: moment()
        },
        remark: {
            value: ''
        }
    };
}

class AddRefund extends Component {
    constructor(props) {
        super(props);
        this.state = {
            info: getParams(),
            visible: false,
            code: false,
            message: '',
            imgSrc: ''
        };
        const _this = this;
        //当前选中的订单号
        this.selectOrderNo = '';
        this.pageSize = 10;
        this.searchParams = {};
        this.columns = [
            {
                title: '放款时间',
                dataIndex: 'loanTime',
                key: 'loanTime',
                render(text) {
                    return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            { title: '订单号', dataIndex: 'orderNo', key: 'orderNo' },
            { title: '姓名', dataIndex: 'userTrueName', key: 'userTrueName' },
            { title: '手机号', dataIndex: 'userPhone', key: 'userPhone' },
            { title: '正常应还金额', dataIndex: 'deviceMoney', key: 'deviceMoney' },
            {
                title: '订单状态',
                dataIndex: 'status',
                key: 'status',
                render(text) {
                    return orderStatus[text];
                }
            },
            {
                title: '应还时间',
                dataIndex: 'expireTime',
                key: 'expireTime',
                render(text) {
                    return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            { title: '应还金额', dataIndex: 'needPayMoney', key: 'needPayMoney' },
            { title: '已还金额', dataIndex: 'hadPaidMoney', key: 'hadPaidMoney' },
            {
                title: '操作',
                dataIndex: 'id',
                key: 'id',
                render(text, record) {
                    return (
                        <div className={styles.recordWrapper}>
                            <Tooltip title={"添加记录"}>
                                <span onClick={() => _this.showModal(record)}><Icon type={'plus'}/></span>
                            </Tooltip>
                            <Tooltip style={{marginLeft: '20px'}} title={"生成二维码"}>
                                <span onClick={() => _this.onCode(record)}><Icon type={'picture'}/></span>
                            </Tooltip>
                        </div>
                    );
                }
            }
        ];
    }

    onChange= (changedFields) => {
        this.setState(({ info }) => ({
            info: { ...info, ...changedFields },
        }));
    }

    onCode = (record) => {
        const {userId} = record;
        axios({
            url: '/hs/admin/order/getRepayQrCode',
            method: 'post',
            data: {
                userId
            }
        }).then((res) => {
            console.log(res)
            const _this = this;
            if(res.data) {
                const data = res.data
                _this.setState({
                    code: true,
                    // imgSrc: `http://api.xjd.mayiaf.com/outserver/api/qrCode?txt=${escape(data.img)}`,
                    imgSrc: `/outserver/api/qrCode?txt=${escape(data.img)}`,
                    message: data.money
                })
            }
        })
    }

    onCancel = () =>{
        this.setState({
            code: false,
            imgSrc: '',
        })
    }

    showModal = (record) => {
        const { orderNo, userTrueName, userPhone, needPayMoney, hadPaidMoney, status, id } = record;
        // const { changeModalVisible } = this.props;
        this.selectOrderNo = orderNo;
        this.setState({
            info: { ...getParams(), userPhone, userTrueName, needPayMoney, hadPaidMoney, status, id }
        }, () => {
            // changeModalVisible(true);
            this.setState({
                visible: true
            })
        });
    }

    handlePageChange = (info) => {
        const { current, pageSize } = info;
        const { getTableData } = this.props;
        getTableData({ ...this.searchParams, pageSize, pageNum: current });
    }
    submit = (obj) => {
        const { getTableData } = this.props;
        this.searchParams = obj;
        getTableData({ pageNum:1, pageSize: this.pageSize, ...this.searchParams });
    }

    handleOk = (obj) => {
        const params = { ...obj, orderNo: this.selectOrderNo };
        const { addTableRecord, getTableData, tableData: { pagination } } = this.props;
        const payTime = params['payTime'].format('YYYY-MM-DD HH:mm:ss');
        params['payTime'] = payTime;
        this.setState({
            visible: false
        })
        addTableRecord(params, () => {
            getTableData({ ...this.searchParams, pageNum: pagination['current'] || 1, pageSize: this.pageSize });
        });
    }
    handleCancel = () => {
        // const { changeModalVisible } = this.props;
        this.setState({
            visible: false
        })
        // changeModalVisible(false);
    }
    componentWillUnmount() {
        const { setTableData } = this.props;
        setTableData({ data: [], pagination: {} });
    }
    render() {
        const { tableData: { data, pagination }, loading, btnLoading, visible } = this.props;
        return (
            <div>
                <SearchList submit={this.submit}/>
                <CommonTable
                    columns={this.columns}
                    handlePageChange={this.handlePageChange}
                    loading={loading}
                    pagination={pagination}
                    dataSource={data}
                />
                <AddModal data={this.props.tableData.data} onChange={this.onChange} handleOk={this.handleOk} handleCancel={this.handleCancel} info={this.state.info} visible={this.state.visible} modalLoading={btnLoading}/>
                <Modal
                    title="二维码"
                    visible={this.state.code}
                    onOk={this.onCancel}
                    onCancel={this.onCancel}
                    >
                    <h2 style={{textAlign:'center'}}>金额：{this.state.message}元</h2>
                    <p style={{textAlign:'center'}}><img src={this.state.imgSrc} /></p>
                    <p style={{textAlign:'center'}}>
                        <div>使用支付宝扫码</div>
                        <div>二维码仅限使用一次，若提示“订单号重复”，请重新生成。</div>
                    </p>
                </Modal>
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    const { paymentManageState: { addRefundState } } = state;
    return {
        tableData: addRefundState['tableData'],
        loading: addRefundState['loading'],
        visible: addRefundState['visible'],
        btnLoading: addRefundState['btnLoading']
    }
}

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        getTableData: addRefundAction.ardGetTableData,
        setTableData: addRefundAction.ardSetTableData,
        changeModalVisible: addRefundAction.ardChangeVisible,
        addTableRecord: addRefundAction.ardAddTableRecord
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(AddRefund);